package controllers

import (
	"fmt"
	"math"
	"myerp/models"
	"myerp/src"
	"strconv"
	"time"
)

//财务管理
type FinanceController struct {
	CommonController
}

//添加  前段写一下验证
func (c *FinanceController) Add() {
	if c.Ctx.Request.Method == "POST" {
		reData := make(map[string]interface{})
		reData["status"] = 1
		// var name, spec, gmodel, units string
		// var sorteid, status, salestatus int
		// var price float64
		var md models.Finance
		if err := c.ParseForm(&md); err != nil {
			//handle error
		}
		md.Pcode = src.OrderNumber("FP")
		md.Pctime = int(time.Now().Unix())
		md.Uid = int(UserInfo.Id)
		fmt.Println(md)
		_, err := models.AddFinance(&md)
		if err != nil {
			reData["msg"] = "添加财务记录失败！"
		} else {
			reData["url"] = "/finance/list"
			reData["status"] = 1
		}
		c.Data["json"] = reData
		c.ServeJSON()
	}
	c.Layout = "base.html"
	c.TplName = "finance/add.html"
}

//编辑
func (c *FinanceController) Edite() {
	var id int
	if c.Ctx.Request.Method == "POST" {
		var md models.Finance
		err := models.UpdateFinanceById(&md)
		if err != nil {
			c.Data["st"] = 0
			c.Data["message"] = "修改失败"
			c.Data["uri"] = "/personnel/edite?id=" + c.GetString("Id")
		} else {
			c.Data["message"] = "修改成功"
			c.Data["uri"] = "/personnel/list"
			c.Data["st"] = 1
		}
		c.TplName = "error.html"
		return
	}

	id, err := c.GetInt("id")
	if err != nil {
		c.Data["message"] = "修改的内容不存在"
		c.Data["uri"] = "/personnel/list"
		c.Data["st"] = 0
		c.TplName = "error.html"
		return
	}
	sd, err := models.GetFinanceById(id)
	if err != nil {
		c.Data["message"] = "修改的内容不存在"
		c.Data["uri"] = "/personnel/list"
		c.Data["st"] = 0
		c.TplName = "error.html"
		return
	}
	c.Data["Sdata"] = sd
	c.Layout = "base.html"
	c.TplName = "finance/edite.html"
}

//列表
func (c *FinanceController) List() {
	c.Data["ActionName"] = "财务明显"
	var query map[string]string
	var fields []string
	var sortby []string
	var order []string
	var offset int64
	var limit int64 = 10
	var page int64
	count, _ := models.GetAllFinanceCount(query)
	page, _ = c.GetInt64("page", 0)
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * limit
	}
	if page*limit > count {
		if limit > count {
			offset = 0
		} else {
			s := math.Floor(float64(count)/float64(limit)) * float64(limit)
			offset = int64(s)
		}
	}

	l, _ := models.GetAllFinance(query, fields, sortby, order, offset, limit)
	c.Data["List"] = l
	var pages src.Page = src.NewPage(int(page), 10, int(count), "/finance/list")
	c.Data["page"] = pages.Show()
	c.Layout = "base.html"
	c.TplName = "finance/list.html"
}

func (c *FinanceController) Delete() {
	Id := c.GetString("id")
	resId, _ := strconv.Atoi(Id)
	err := models.DeleteFinance(resId)
	reData := make(map[string]interface{})
	reData["status"] = 0
	reData["msg"] = "删除失败！"
	if err == nil {
		reData["status"] = 1
		reData["msg"] = "删除成功"
	}
	c.Data["json"] = reData
	c.ServeJSON()
}
